//
//  OYComposeController.swift
//  weiboCopycat
//
//  Created by Orange Yu on 2016/12/9.
//  Copyright © 2016年 Orange Yu. All rights reserved.
//

import UIKit
import SVProgressHUD

class OYComposeController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.white
        
        setupUI()
    }
    


     // MARK: -控件的懒加载
    lazy var sendButton:UIButton = {
        let button = UIButton(type: .custom)
        button.addTarget(self, action: #selector(sendAction), for: .touchUpInside)
        
        button.setTitle("发送", for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.gray, for: .disabled)
        button.setBackgroundImage(UIImage(named:"common_button_orange"), for: .normal)
        button.setBackgroundImage(UIImage(named:"common_button_white_disable"), for: .disabled)
        button.setBackgroundImage(UIImage(named:"common_button_orange_highlighted"), for: .highlighted)
        
        
        button.frame.size = CGSize(width: 40, height: 30)
//        button.sizeToFit()
        return button
    }()
    
    lazy var navTitleLabel:UILabel = {
        let titleLabel = UILabel()
        
        titleLabel.numberOfLines = 2
        titleLabel.textAlignment = .center
        
        // 创建富文本
        let name = (OYUserInfoViewModel.sharedUserInfo.userInfo?.screen_name)!
        let title:String = "发微博\n\(name)"
        let attributedTitle: NSMutableAttributedString = NSMutableAttributedString(string: title)
        // 确定需要修改样式的range
        let range = (title as NSString).range(of: name)
        // 设置修改的样式
        attributedTitle.addAttributes([NSForegroundColorAttributeName:UIColor.lightGray,NSFontAttributeName:UIFont.systemFont(ofSize: 12)], range: range)
        // 为titlelabel赋值
        titleLabel.attributedText = attributedTitle
        //        let attributeString: NSMutableAttributedString = NSMutableAttributedString()
        titleLabel.sizeToFit()
        return titleLabel
    }()
    
    lazy var textView:OYTextView = {
        let textView = OYTextView()
        textView.font = UIFont.systemFont(ofSize: 14)
        textView.delegate = self

        textView.alwaysBounceVertical = true
        return textView
    }()
    
    lazy var toolBar:OYToolBar = {
        let stackView = OYToolBar()
        stackView.axis = .horizontal
        stackView.distribution = .equalSpacing
        return stackView
    }()
    
    lazy var pictureView:OYPickerCollectionView = {
        let pictureView = OYPickerCollectionView()
        
        return pictureView
    }()
    
    lazy var emotionKeyboardView: OYEmotionView = {
        let emotionView = OYEmotionView()
        
        emotionView.size = CGSize(width: ScreenWidth, height: 216)
        
        return emotionView
    }()
    
     // MARK: -UI搭建
    func setupUI() {
        // 接收键盘弹出的通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardFrameChange(noti:)), name: Notification.Name.UIKeyboardWillChangeFrame, object: nil)
        // 接收选中表情的通知
        NotificationCenter.default.addObserver(self, selector: #selector(emotionBtnSelected(noti:)), name: NSNotification.Name(rawValue: EmotionButtonActionNotification), object: nil)
        // 接收删除表情按钮发送的通知
        NotificationCenter.default.addObserver(self, selector: #selector(deleteBtnSelected), name: NSNotification.Name(DeleteButtonActionNotification), object: nil)
        
        // 设置导航栏
        setupNavUI()
        
         // MARK: -解决textView的顶部因为scrollView在navigationController下而有64间距的问题
        self.automaticallyAdjustsScrollViewInsets = false
        
        // 添加子控件
        view.addSubview(textView)
        view.addSubview(toolBar)
        view.addSubview(pictureView)
        // 布局子控件
        textView.snp_makeConstraints { (make) in
            make.top.equalTo(view).offset(64)
//            make.top.equalTo(topLayoutGuide)
            make.left.right.equalTo(self.view)
//            make.bottom.equalTo(toolBar.snp_top)
            make.height.equalTo(100)
        }
        
        
        let leftMargin:CGFloat = 10
        let pictureViewW = ScreenWidth - 2 * leftMargin
        pictureView.snp_makeConstraints { (make) in
            make.size.equalTo(CGSize(width: pictureViewW, height: pictureViewW))
//            make.top.equalTo(self.view).offset(100)
            make.top.equalTo(textView.snp_bottom)
            make.centerX.equalTo(view)
        }
        
        toolBar.snp_makeConstraints { (make) in
            make.leading.equalTo(view).offset(15)
            make.trailing.equalTo(view).offset(-15)
            make.bottom.equalTo(view)
            make.height.equalTo(35)
        }
        
        toolBar.closure = { (type) in
            switch type {
            case .picture:
                self.didSelectedPicture()
            case .mention:
                print("@")
            case .trend:
                print("话题")
            case .emoticon:
                self.didSelectEmotion()
            case .plus:
                print("添加")
                
            }
        }
        
        pictureView.closure = { [weak self] in
            self?.didSelectedPicture()
        }
        
     
    }
    
     // MARK: -监听表情键盘删除按钮的通知(来自OYEmotionViewCell)
    func deleteBtnSelected() {
        self.textView.deleteBackward()
    }
    
     // MARK: -监听表情选中的通知(来自OYEmotionViewcell)
    func emotionBtnSelected(noti:Notification) {
       
        let emotionModel = noti.object as! OYEmotionModel
     
//        print("选中了\(emotionModel.chs)表情")
        // 将选中的表情添加至最近表情数组中
        OYEmotionTools.sharedTools.addRecentEmotion(emotionModel: emotionModel)
        // 刷新CollectionView
        emotionKeyboardView.reloadRecentEmotionCell()
        
        // 将表情转换为富文本显示在textView上
        textView.insertEmotion(emotionModel: emotionModel)
        
    }
    
    // MARK: -监听键盘frame改变的通知
    func keyBoardFrameChange(noti:Notification) {
        let userInfo:[String:Any] = noti.userInfo as! [String : Any]
        let animationTime:Double = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let keyboardFrame:CGRect = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        
        toolBar.snp_updateConstraints { (make) in
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - ScreenHeight)
        }
        
        UIView.animate(withDuration: animationTime) {
            self.view.layoutIfNeeded()
        }
    }
    
     // MARK: -导航栏设置
    func setupNavUI() {
    // 设置导航栏左边的取消
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imageName: nil, target: self, action: #selector(dismissAction))
        
        // 设置导航栏右边的发送
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        self.navigationItem.rightBarButtonItem?.isEnabled = false
        // 设置中间titleView标题
        self.navigationItem.titleView = navTitleLabel
    }
    
    
     // MARK: -返回MainController
    func dismissAction() {
        view.endEditing(true)
        self.dismiss(animated: true, completion: nil)
    }
    
     // MARK: -发送微博
    func sendAction() {
        
         // MARK: -发送微博时能够发送表情
        // 取到textView的attributedText
        let attributeText = textView.attributedText
        var result = ""
        // 遍历富文本，取出自定义富文本附件。获取附件中当前表情的model
        attributeText?.enumerateAttributes(in: NSMakeRange(0, attributeText!.length), options: [], using: { (info, range, _) in
            
             // MARK: -判断富文本中是图片还是文字判断有没有文本附件
            if let attachment = info["NSAttachment"] as? OYEmotionAttachment{
                // 将当前的富文本中的表情富文本修改为对应的表情名称
                let emotionModel = attachment.emotionModel
                let emotionName = emotionModel?.chs
                result += emotionName!
            } else {
                // 文字富文本
                let text = attributeText?.attributedSubstring(from: range).string
                result += text!
            }
        })
        
        let status = result
        
        if pictureView.imageList.count > 0 {
            // 发送带图片的微博
            OYNetWorkTools.sharedTools.postPictureWeibo(status: status, image: pictureView.imageList.first!, callBack: { (response, error) in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "发送失败")
                    return
                }else {
                    SVProgressHUD.showSuccess(withStatus: "发送成功")
                    DispatchQueue.main.async {
//                        self.dismiss(animated: true, completion: nil)
                    }
                }
            })
        }else {
            OYNetWorkTools.sharedTools.postWeibo(status: status) { (response, error) in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "发送失败")
                    return
                }
                SVProgressHUD.showSuccess(withStatus: "发送成功")
                
//                self.dismiss(animated: true, completion: nil)
            }
        }
        
    }
    
}

/// 设置一个监听height改变的变量
var oldHeight:CGFloat = 0
// MARK: - 监听textView文字改变相关属性
extension OYComposeController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        // textView文字发生改变时候，将placeHolder禁用
        self.textView.placeholderLabel.isHidden = true
        // 设置button的禁用需要通过设置rightBarButtonItem
        self.navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
        
        // 设置textView高度自适应
        let width = textView.width
//        let height = textView.height
        let newSize = textView.sizeThatFits(CGSize(width: width, height: CGFloat(MAXFLOAT)))
        //        print(newSize.height)
        if newSize.height != oldHeight && newSize.height > 100 {
            // 更新约束
            self.textView.snp_updateConstraints(closure: { (make) in
                make.height.equalTo(newSize.height)
            })
        }
        UIView.animate(withDuration: 0.25, animations: {
            
            self.view.layoutIfNeeded()
            
        })
        oldHeight = newSize.height

    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        // textView滑动的时候键盘失去第一响应者
        self.view.endEditing(true)
    }
    
}


// MARK: - 点击toolBar相关操作
extension OYComposeController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    /// 表情按钮点击事件
    func didSelectEmotion() {
        // 判断textView中键盘的状态，点击button切换状态
        if textView.inputView == nil {
            textView.inputView = emotionKeyboardView
            toolBar.emoticonButton?.setImage(UIImage(named:"compose_keyboardbutton_background"), for: .normal)
            toolBar.emoticonButton?.setImage(UIImage(named:"compose_keyboardbutton_background_highlighted"), for: .highlighted)
            
        }else {
            textView.inputView = nil
            toolBar.emoticonButton?.setImage(UIImage(named:"compose_emoticonbutton_background"), for: .normal)
            toolBar.emoticonButton?.setImage(UIImage(named:"compose_emoticonbutton_background_highlighted"), for: .highlighted)

            
        }
        
        textView.becomeFirstResponder()
        textView.reloadInputViews()
    }
    
    /// 图片按钮点击事件
    func didSelectedPicture() {
        let pickerViewController: UIImagePickerController = UIImagePickerController()
        pickerViewController.delegate = self
        // 判断pickerViewController内容来源
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            pickerViewController.sourceType = .camera
        }else {
            pickerViewController.sourceType = .photoLibrary
        }
        // 判断前置/后置摄像头是否可用
        if UIImagePickerController.isCameraDeviceAvailable(.front) {
            print("前置摄像头可用")
        }
        if UIImagePickerController.isCameraDeviceAvailable(.rear) {
            print("后置摄像头可用")
        }
        
        self.present(pickerViewController, animated: true, completion: nil)
        
    }
    
    /// 在pickervc中选择完毕图片之后将图片进行保存
    ///
    /// - Parameters:
    ///   - picker: pickvc控制器
    ///   - info: 选择的图片的信息
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        // 从info中拿到图片
        let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
        // 进行压缩
        let zipImage = self.zipImage(image: selectedImage)
        // 将图片传递给CollectionView用于显示
        pictureView.addImage(image: zipImage)
        // 将当前控制器dismiss
        picker.dismiss(animated: true, completion: nil)
        
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
    func zipImage(image:UIImage) -> UIImage {
        // 拿到图片的尺寸
        let size = image.size
        // 设置一个期望压缩的宽度
        let expectedWidth:CGFloat = 200
        // 计算需要压缩的高度
        let expectedHeight:CGFloat = size.height * (expectedWidth / size.width)
        let expectedSize:CGSize = CGSize(width: expectedWidth, height: expectedHeight)
        // 返回压缩后的图片
        // 开启图片上下文
        UIGraphicsBeginImageContext(expectedSize)
        // 把图片渲染到指定区域内
        image.draw(in: CGRect(origin: CGPoint.zero, size: expectedSize))
        // 从上下文中获取压缩后的图片
        let zipImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        // 关闭图片上下文
        UIGraphicsEndImageContext()
        return zipImage
    }
    
}
